<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const form = reactive({
  name: ''
})

/* ---- */
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = () => {
  if (proxy.$route.query.id) {
    proxy.$http.get('common-type/index', {
      params: { 'CommonTypeSearch[id]': proxy.$route.query.id }
    }).then((res) => {
      if (Number(res.items.length) > 0) form.name = res.items[0].name
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
}
// ----
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合作商家分类名称！')
    return false
  }
  // ----
  let forType = 'post'
  let forUrl = 'common-type/create'
  let forData = {
    dealer_id: logUser.id,
    // --合作商家分类--
    type: 1,
    // ----
    name: form.name,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'common-type/update?id=' + proxy.$route.query.id
    forData = {
      name: form.name,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) proxy.$router.back()
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-are xw-radius-3">
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.name"></textarea></p>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>
